Crate yazi

source ·
Expand description

Yet another zlib implementation.

This crate is an implementation of the RFC 1950 DEFLATE specification with support for the zlib wrapper. There are many fine options for such in the Rust ecosystem, but I was looking for one that was small and relatively simple with reasonable performance/compression ratio and support for heap-free compression/decompression scenarios. This crate aims to tick those boxes while also providing composable streaming support based on the standard I/O mechanisms.

See the quick start guide below for basic usage or jump to the compression or decompression section for more detail.

Quick Start

So you’ve got some bytes, they all fit in memory, you don’t need to reuse allocations, and you just want to compress or decompress them. This section is for you.

Cargo.toml:

[dependencies]
yazi = "0.1.4"

The compress and decompress functions are provided for the most common use cases:

use yazi::*;
// Your source data.
let data = &(0..=255).cycle().take(8192).collect::<Vec<u8>>()[..];
// Compress it into a Vec<u8> with a zlib wrapper using the default compression level.
let compressed = compress(data, Format::Zlib, CompressionLevel::Default).unwrap();
// Decompress it into a Vec<u8>.
let (decompressed, checksum) = decompress(&compressed, Format::Zlib).unwrap();
// Verify the checksum.
assert_eq!(Adler32::from_buf(&decompressed).finish(), checksum.unwrap());
// Verify that the decompressed data matches the original.
assert_eq!(&decompressed[..], data);

Read on for more detailed usage.

Compression

To compress data, you’ll need to create an instance of the Encoder struct. The new method can be used to construct an encoder on the stack, but the internal buffers are large (~300k) and may cause a stack overflow so it is advisable to use the boxed method to allocate the encoder on the heap.

Newly constructed encoders are configured to output a raw DEFLATE bitstream using a medium compression level and a default strategy. Call set_format to change the output Format. Raw DEFLATE and zlib are supported. The set_level method allows you to choose the preferred CompressionLevel from a set of basic options or a specific level between 1 and 10. The CompressionStrategy can be changed with the set_strategy method. This allows you to, for example, force the encoder to output only static blocks.

To create an encoder that outputs a zlib bitstream and spends some extra time to potentially produce a result with a higher compression ratio:

use yazi::{CompressionLevel, Encoder, Format};
let mut encoder = Encoder::boxed();
encoder.set_format(Format::Zlib);
encoder.set_level(CompressionLevel::BestSize);

The encoder itself does not provide any functionality. It simply stores state and configuration. To actually compress data, you’ll need an EncoderStream. A stream is a binding between an encoder and some specific output that will receive the compressed data. This design allows an encoder to be reused with different types of outputs without paying the allocation and initialization cost each time.

Streaming supports outputs of the following forms:

Once you have an EncoderStream, simply call write one or more times, feeding your raw data into the stream. If available, you can submit the entire input buffer at once, or in arbitrarily sized chunks down to a single byte. After all data has been written, call finish on the stream which will consume it, flush all remaining input and output, and finalize the operation. The finish method returns a Result containing the total number of compressed bytes written to the output on success, or an Error describing the problem on failure.

Let’s write a function that compresses some arbitrary bytes into a vector:

fn compress_bytes(buf: &[u8]) -> Result<Vec<u8>, yazi::Error> {
    use yazi::Encoder;
    let mut encoder = Encoder::boxed();
    let mut vec = Vec::new();
    let mut stream = encoder.stream_into_vec(&mut vec);
    stream.write(buf)?;
    stream.finish()?;
    Ok(vec)
}

Now let’s do something a bit more interesting, and given two paths, compress one file into another:

fn compress_file(source: &str, dest: &str) -> Result<u64, yazi::Error> {
    use yazi::Encoder;
    use std::fs::File;
    use std::io::{copy, BufWriter};
    let mut encoder = Encoder::boxed();
    // yazi does not perform any internal buffering beyond what is necessary
    // for correctness.
    let mut target = BufWriter::new(File::create(dest)?);
    let mut stream = encoder.stream(&mut target);
    copy(&mut File::open(source)?, &mut stream)?;
    stream.finish()
}

Here, we can see that EncoderStream also implements Write, so we can pass it directly to std::io::copy. This allows streams to be composable with the standard I/O facilities and other libraries that support those interfaces.

Decompression

If you’ve already read the section on compression, the API for decompression is essentially identical with the types replaced by Decoder and DecoderStream. The documentation is copied here almost verbatim for the sake of completeness and for those who might have skipped directly to this section.

To decompress data, you’ll need to create an instance of the Decoder struct. The new method can be used to construct a decoder on the stack, and unlike encoders, the decoder struct is relatively small (~10k) and generally safe to stack allocate. You can create a decoder on the heap with the boxed method if you prefer.

Newly constructed decoders are configured to decompress a raw DEFLATE bitstream. Call set_format to change the input Format. Raw DEFLATE and zlib are supported. No other configuration is necessary for decompression.

To create a decoder that decompresses a zlib bitstream:

use yazi::{Decoder, Format};
let mut decoder = Decoder::new();
decoder.set_format(Format::Zlib);

The decoder itself does not provide any functionality. It simply stores state and configuration. To actually decompress data, you’ll need a DecoderStream. A stream is a binding between a decoder and some specific output that will receive the decompressed data. This design allows a decoder to be reused with different types of outputs without paying the allocation and initialization cost each time.

Streaming supports outputs of the following forms:

Once you have a DecoderStream, simply call write one or more times, feeding your compressed data into the stream. If available, you can submit the entire input buffer at once, or in arbitrarily sized chunks down to a single byte. After all data has been written, call finish on the stream which will consume it, flush all remaining input and output, and finalize the operation. The finish method returns a Result containing the total number of decompressed bytes written to the output along with an optional Adler-32 checksum (if the stream was zlib-encoded) on success, or an Error describing the problem on failure.

Let’s write a function that decompresses a zlib bitstream into a vector and verifies the checksum:

fn decompress_zlib(buf: &[u8]) -> Result<Vec<u8>, yazi::Error> {
    use yazi::{Adler32, Decoder, Error, Format};
    let mut decoder = Decoder::new();
    decoder.set_format(Format::Zlib);
    let mut vec = Vec::new();
    let mut stream = decoder.stream_into_vec(&mut vec);
    stream.write(buf)?;
    // checksum is an Option<u32>
    let (_, checksum) = stream.finish()?;
    if Adler32::from_buf(&vec).finish() != checksum.unwrap() {
        return Err(Error::InvalidBitstream);
    }
    Ok(vec)
}

Now let’s do something a bit more interesting, and given two paths, decompress one file into another:

fn decompress_file(source: &str, dest: &str) -> Result<(u64, Option<u32>), yazi::Error> {
    use yazi::Decoder;
    use std::fs::File;
    use std::io::{copy, BufWriter};
    let mut decoder = Decoder::new();
    // yazi does not perform any internal buffering beyond what is necessary
    // for correctness.
    let mut target = BufWriter::new(File::create(dest)?);
    let mut stream = decoder.stream(&mut target);
    copy(&mut File::open(source)?, &mut stream)?;
    stream.finish()
}

Here, we can see that DecoderStream also implements Write, so we can pass it directly to std::io::copy. This allows streams to be composable with the standard I/O facilities and other libraries that support those interfaces.

Implementation Notes

The compressor is based heavily on both miniz (https://github.com/richgel999/miniz) by Rich Geldreich and miniz_oxide (https://github.com/Frommi/miniz_oxide) by Frommi. The available compression levels and strategies are the same and it should produce an identical bitstream for a given set of options. The decompressor is based on the techniques in libdeflate (https://github.com/ebiggers/libdeflate) by Eric Biggers.

Structs

  • Rolling Adler-32 checksum.
  • Stateful context for decompression.
  • Decompression stream combining a decoder context with an output.
  • Stateful context for compression.
  • Compression stream combining an encoder context with an output.

Enums

  • The level of compression– a compromise between speed and size.
  • Selects between various specialized compressor modes.
  • Errors that may occur during compression or decompression.
  • Defines the format for a compressed bitstream.

Functions

  • Compresses a buffer into a vector with the specified format and compression level.
  • Decompresses a buffer of the specified format into a vector.